﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using Code.Models;
using QianBuo.Lottery.Web.Models;
using Code.Commen;
using QianBuo.Lottery.Web.Models.Account;
using QianBuo.Lottery.Web.Models.Surrogate;
using QianBuo.Lottery.Web.Models.User;
using System.Text.RegularExpressions;

namespace QianBuo.Lottery.Web.Controllers
{
    public class SurrogateController : BaseController
    {
        //
        // GET: /Surrogate/


        #region 添加用户
        public ActionResult Add()
        {
            var model = new AddUser();
            if (LoginUser.UserType != UserType.Surrogate)
                return Content("';history.go(-1);'".Redirect("您不是代理"));
            var accm = new AddChildConfigManage();
            UserAddChildConfig temp = null;
            model.EnableAddChildConfig = CacheManage.OptionSite[Option_Site_Key.Site_AddChildConfig_Enable].ToBool(false);
            temp = accm.GetNowAddChildConfig(LoginUserID);

            if (temp.State == (short)AddChildConfigState.Locked)
            {
                ViewData["msg"] = "您的添加下级功能已被锁定，请和上级或管理员联系!".AlertOffPage();
                ViewData["btnAddDisabled"] = true;
            }
            else if (model.EnableAddChildConfig && temp.AllChildCount <= 0)
            {
                ViewData["msg"] = "您的可添加下级名额已用完，您目前不能添加下级!".AlertOffPage();
                ViewData["btnAddDisabled"] = true;
            }
            else
                ViewData["btnAddDisabled"] = false;
            var MemberMaxSetRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            model.MaxBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            if (model.MaxBackMoneyRatio >= 100 || model.MaxBackMoneyRatio < 0)
                model.MaxBackMoneyRatio = null;
            model.AllChildCount = temp.AllChildCount;
            PlayTypeOptionManage PM = new PlayTypeOptionManage();
           
            model.Options = PM.AddGetOption_Set(LoginUserID, 1, null, true).ToArray();
            model.Options.Each(p => p.MaxBackMoneyRatio = Math.Min(MemberMaxSetRatio, p.MaxBackMoneyRatio));
            foreach (var item in model.Options)
            {
                if (CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false)==false)
                {
                    item.Option.BackMoneyRatio = 0.0;
                }
                item.Option.WinMoneyState = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
            }
            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            return View(model);
        }

        [HttpPost]
        public ActionResult Add(AddUser model)
        {
            model.MaxBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            model.EnableAddChildConfig = CacheManage.OptionSite[Option_Site_Key.Site_AddChildConfig_Enable].ToBool(false);
            if (model.MaxBackMoneyRatio >= 100)
                model.MaxBackMoneyRatio = null;
            int count = 0;
            PlayTypeOptionManage PM = new PlayTypeOptionManage();
            var MemberMaxSetRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            model.MaxBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            if (model.MaxBackMoneyRatio >= 100 || model.MaxBackMoneyRatio < 0)
                model.MaxBackMoneyRatio = null;
            if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true)
            {
                 int couts = 0;
                foreach (var item in model.Options)
                {
                    if (item.States == false)
                    {
                        couts++;
                    }
                }

                if (couts == model.Options.Count())
                {
                    ViewData["msg"] = Url.Action("Add").Redirect("您添加的会员必须拥有至少一个模式!");
                    return View(model);
                }
            }
           
           
            if (ModelState.IsValid)
            {
                Guid? newUid;
                string msg;
                UserManage um = new UserManage();
                count = um.AddUser(LoginUserID, model.LoginName, model.LoginPwd, model.Type, model.EnableAddChildConfig, model.AllChildCount ?? 0, false, true, out newUid, out msg);
                if (count > 0)
                {
                    //请确保新增用户时已经设置该用户的奖金

                    count = PM.SetOptionByMargin(LoginUserID, newUid.Value, null, null, model.WinMoneyMargin, 0, true, false);
                    int Insert = PM.InsertUpRank(model.LoginName);

                    if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true && CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false))
                    {
                        List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                        foreach (var item in model.Options)
                        {
                            int winId = item.Option.WinMoneyModelID;
                            int num = 0;
                            foreach (var MyWinId in model.Options)
                            {
                                if (winId == MyWinId.Option.WinMoneyModelID)
                                {
                                    model.Options[num].States = item.States;
                                }
                                num++;
                            }

                        }
                        foreach (var item in model.Options)
                        {
                            Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                            back.BackMoneyRatio = item.Option.BackMoneyRatio;
                            back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                            back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                            var winId = item.Option.WinMoneyModelID;
                            back.States = item.States;
                            list.Add(back);
                        }
                        PM.Updatewin(list, model.LoginName);

                    }

                    if (CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false) == false)
                    {
                            List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                            foreach (var item in model.Options)
                            {
                                int winId = item.Option.WinMoneyModelID;
                                int num = 0;
                                foreach (var MyWinId in model.Options)
                                {
                                    if (winId == MyWinId.Option.WinMoneyModelID)
                                    {
                                        model.Options[num].States = item.States;
                                    }
                                    num++;
                                }
                            }

                            if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true)
                            {
                                int cout = 0;
                                foreach (var item in model.Options)
                                {
                                    if (item.States == false)
                                    {
                                        cout++;
                                    }
                                }

                                if (cout == model.Options.Count())
                                {

                                    ViewData["msg"] = Url.Action("Add").Redirect("您添加的会员必须拥有至少一个模式!");
                                    return View(model);
                                }
                                foreach (var item in model.Options)
                                {
                                    Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                                    back.BackMoneyRatio = item.Option.BackMoneyRatio;
                                    back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                                    back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                                    var winId = item.Option.WinMoneyModelID;
                                    back.States = item.States;
                                    list.Add(back);
                                }
                                int result = PM.LoginUpdateOption(list, model.LoginName);
                            }
                            else
                            {
                                foreach (var item in model.Options)
                                {
                                    Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                                    back.BackMoneyRatio = item.Option.BackMoneyRatio;
                                    back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                                    back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                                    var winId = item.Option.WinMoneyModelID;
                                    back.States = true;
                                    list.Add(back);
                                }
                                int update = PM.LoginUpdateUserOption(list, model.LoginName);


                            }
                         
                        
                    }
                        if (count < 0)
                            //msg = "<script>if(confirm('新增用户成功!\\r\\n但奖金/反点未设置成功\\r\\n是否现在设置返奖?'))location.href='" + Url.Action("PlayTypeOptionForm", new { uid = newUid, returnUrl = Request.RawUrl }) + "';else location.href='" + Url.Action("Add") + "'</script>";
                            ViewData["msg"] = Url.Action("PlayTypeOptionFrom", new { uid = newUid, returnUrl = Request.RawUrl }).Redirect("新增用户成功!\\r\\n但奖金/反点未设置成功\\r\\n是否现在设置返奖?", Url.Action("Add"));
                        else

                            msg = "新增用户成功!";
                        if (string.IsNullOrEmpty(msg))
                            msg = "操作失败，请稍后再试！";
                }
                if (msg.Length > 15)
                {
                    ModelState.AddModelError("Error", msg);
                    msg = "";
                }
                else
                    msg = Url.Action("Add").Redirect(msg); ;
                ViewData["msg"] = msg;
            }
            return View(model);
        }

        #endregion

        #region 会员列表
        public ActionResult AllChild(Guid? userID, AllChildModel allChildModel)
        {
            UserManage um = new UserManage();
            if (userID.HasValue && userID.Value != LoginUserID)
            {
                var user = um.Select(s => s.FirstOrDefault(p => p.ID == userID.Value));
                if (user == null)
                {
                    userID = LoginUserID;
                    ViewData["msg"] = "您要查找的下级不存在".AlertOffPage();
                }
                else
                {
                    if (!user.Commands.Contains(LoginUserID.ToString()))
                    {
                        userID = LoginUserID;
                        ViewData["msg"] = "您要查找的下级不存在".AlertOffPage();
                    }
                }
            }

            AllChildModel model;
            if (allChildModel != null)
            {
                model = allChildModel;
            }
            else
            {
                model = new AllChildModel();
            }
            if (model.PageInfo == null)
            {
                model.PageInfo = new PageInfo();
            }
            model.LoginUserID = LoginUserID;

            Guid id = userID.HasValue ? userID.Value : LoginUserID;
            string where = " 1==1 ";
            List<object> param = new List<object>();

            IEnumerable<AllChild_Mod> allChild;
            if (model.Where != null && !string.IsNullOrEmpty(model.Where.ChildName))
            {
                var list = um.Select(s => s.Where(p => p.LoginName == model.Where.ChildName.Trim() && p.Commands.Contains(LoginUserID.ToString())).Select(p =>
                    new
                    {
                        Balance = p.Account.Balance,
                        ChildName = p.LoginName,
                        RegistTime = p.RegistTime,
                        State = p.State,
                        Type = p.UserType,
                        ID = p.ID,
                        p.CommandID,
                        LastLoginTime = p.LoginLog.OrderByDescending(p1 => p1.LoginTime).Select(p1 => new { Time = p1.LoginTime }).FirstOrDefault()
                    })).ToArray();
                var user = list.FirstOrDefault();
                if (user == null
                    || (model.Where.Type == AllChidl_Where_Type.DowLine) && OnLineUsers.Select(p => p.Value.UserID).Contains(user.ID)
            || (model.Where.Type == AllChidl_Where_Type.OnLine) && !OnLineUsers.Select(p => p.Value.UserID).Contains(user.ID)
            || (model.Where.Type == AllChidl_Where_Type.Poor) && user.Balance != 0
                    || (model.Where.Type == AllChidl_Where_Type.Richly) && user.Balance == 0
                    || (model.Where.Type == AllChidl_Where_Type.RegestNow) && user.RegistTime.Date != DateTime.Today)
                {
                    ViewData["msg"] = "您要查找的下级不存在".AlertOffPage();
                    model.Parents = um.GetUserParent(LoginUserID).Where(p => p.Uid == LoginUserID || p.Commands.Contains(LoginUserID.ToString())).ToArray();
                    model.ChildsCount = um.GetUserChilds(LoginUserID).Count();
                    GetWhere(model.Where, out where, out param);
                    allChild = um.GetUserChild(id, false, where, param.ToArray());
                }
                else
                {
                    id = user.ID;
                    if (user.CommandID.HasValue)
                    {
                        model.Parents = um.GetUserParent(user.CommandID.Value).Where(p => p.Uid == LoginUserID || p.Commands.Contains(LoginUserID.ToString())).ToArray();
                        model.ChildsCount = um.GetUserChilds(user.CommandID.Value).Count();
                    }
                    allChild = list.Select(p => new AllChild_Mod
                    {
                        Uid = p.ID,
                        ChildName = p.ChildName,
                        Balance = (double)p.Balance,
                        RegistTime = p.RegistTime,
                        LastLoginTime = p.LastLoginTime == null ? null : (DateTime?)p.LastLoginTime.Time,
                        State = (UserState)p.State,
                        Type = p.Type
                    });
                }
            }
            else
            {
                model.Parents = um.GetUserParent(id).Where(p => p.Uid == LoginUserID || p.Commands.Contains(LoginUserID.ToString())).ToArray();
                model.ChildsCount = um.GetUserChilds(id).Count();
                if (model.Where != null)
                    GetWhere(model.Where, out where, out param);
                allChild = um.GetUserChild(id, false, where, param.ToArray());
            }


            if (model.Where != null && model.Where.Type == AllChidl_Where_Type.OnLine)
            {
                var onlineUser = OnLineUsers.Where(p => p.Value.Commands.EndsWith(id.ToString())).ToList();
                model.PageInfo.SunCount = onlineUser.Count;
                onlineUser = onlineUser.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount).ToList();
                allChild = allChild.Where(p => onlineUser.Select(p1 => p1.Value.UserID).Contains(p.Uid)).OrderBy(p => p.RegistTime).ToArray();

                allChild = allChild.Select(p => new AllChild_Mod
                {
                    Balance = p.Balance,
                    ChildsCount = p.ChildsCount,
                    ChildName = p.ChildName,
                    LastLoginTime = p.LastLoginTime,
                    RegistTime = p.RegistTime,
                    Uid = p.Uid,
                    Type = p.Type,
                    State = p.State,
                    OnlineState = UserOnlineState.OnLine
                });
            }
            else if (model.Where != null && model.Where.Type == AllChidl_Where_Type.DowLine)
            {
                var onlineUser = OnLineUsers.Where(p => p.Value.Commands.EndsWith(id.ToString())).ToList();
                allChild = allChild.Where(p => !onlineUser.Select(p1 => p1.Value.UserID).Contains(p.Uid)).OrderBy(p => p.RegistTime).ToArray();
                model.PageInfo.SunCount = allChild.Count();
                allChild = allChild.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount);

                allChild = allChild.Select(p => new AllChild_Mod
                {
                    Balance = p.Balance,
                    ChildsCount = p.ChildsCount,
                    ChildName = p.ChildName,
                    LastLoginTime = p.LastLoginTime,
                    RegistTime = p.RegistTime,
                    Uid = p.Uid,
                    Type = p.Type,
                    State = p.State,
                    OnlineState = UserOnlineState.DowLine
                });
            }
            else
            {
                var count = allChild.Count();
                model.PageInfo.SunCount = count;
                allChild = allChild.OrderBy(p => p.RegistTime).Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount).ToArray();

                allChild = allChild.Select(p => new AllChild_Mod
                {
                    Balance = p.Balance,
                    ChildsCount = p.ChildsCount,
                    ChildName = p.ChildName,
                    LastLoginTime = p.LastLoginTime,
                    RegistTime = p.RegistTime,
                    Uid = p.Uid,
                    Type = p.Type,
                    State = p.State,
                    OnlineState = base.OnLineUsers.ContainsKey(p.Uid) ? (base.OnLineUsers[p.Uid] == null ? UserOnlineState.DowLine : UserOnlineState.OnLine) : UserOnlineState.DowLine
                });
            }

            if (id == model.LoginUserID)
                model.NoAccountChilds = um.GetNoAccountUsers(DateTime.Now.AddDays(-7), id).ToList();
            else
                model.NoAccountChilds = new List<User_Comm>();

            model.UserID = id;
            model.Childs = allChild;
            return View(model);
        }
        [HttpPost]
        public ActionResult AllChild(AllChildModel model)
        {
            if (ModelState.IsValid)
            {
                return AllChild(null, model);
            }
            return AllChild(null, null);
        }
        private void GetWhere(AllChild_Where model, out string where, out List<object> param)
        {
            where = " 1==1 ";
            param = new List<object>();
            string url = "";
            if (model == null)
            {
                ViewData["url"] = url;
                return;
            }
            if (model.Type == AllChidl_Where_Type.RegestNow)
            {
                model.StartTime = DateTime.Today;
                model.EndTime = DateTime.Today;
            }
            if (model.StartTime != null)
            {
                where += " and RegistTime>=@" + param.Count;
                param.Add(model.StartTime.Value);
                url = "&Where.StartTime=" + model.StartTime;
            }
            if (model.EndTime != null)
            {
                where += " and RegistTime<@" + param.Count;
                param.Add(model.EndTime.Value.AddDays(1));
                url = "&Where.EndTime=" + model.EndTime;
            }
            if (model.MaxMoney != null && model.Type != AllChidl_Where_Type.Poor && model.Type != AllChidl_Where_Type.Richly)
            {
                where += " and Balance <=@" + param.Count;
                param.Add(model.MaxMoney);
                url = "&Where.MaxMoney=" + model.MaxMoney;
            }
            if (model.MinMoney != null && model.Type != AllChidl_Where_Type.Poor && model.Type != AllChidl_Where_Type.Richly)
            {
                if (model.Type == AllChidl_Where_Type.Poor)
                    where += " and Balance >@" + param.Count;
                else
                    where += " and Balance >=@" + param.Count;
                param.Add(model.MinMoney);
                url = "&Where.MinMoney=" + model.MinMoney;
            }
            if (model.Type.HasValue && model.Type == AllChidl_Where_Type.Richly)
            {
                where += " and Balance>0";
            }
            else if (model.Type.HasValue && model.Type == AllChidl_Where_Type.Poor)
            {
                where += " and Balance=0";
            }
            ViewData["url"] = url;
        }


        [HttpPost]
        public ActionResult ChildView(string name)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(name))
                    return ChildView((Guid?)null);
                if (um == null)
                    um = new UserManage();
                var user = um.Select(s => s.FirstOrDefault(p => p.LoginName == name));
                if (user == null)
                {
                    ViewData["msg"] = "您查找的用户不存在".AlertOffPage();
                    return ChildView((Guid?)null);
                }
                return ChildView(user.ID);
            }
            return ChildView((Guid?)null);
        }
        UserManage um;
        public ActionResult ChildView(Guid? id)
        {
            if (um == null)
                um = new UserManage();
            var data = um.Select(s => s);
            TreeViewEntity model = null;
            var user = new User_Comm { LoginName = LoginUser.LoginName, Uid = LoginUserID, UserTye = (short)LoginUser.UserType };
            if (!id.HasValue)
            {
                id = LoginUserID;
                data = data.Where(p => p.CommandID == id);
                model = PassTreeView(user, data.ToArray().Select(p => new User_Comm { LoginName = p.LoginName, Uid = p.ID, CommandID = p.CommandID, Commmands = p.Commands, UserTye = p.UserType }));
            }
            else
            {
                currentid = id.Value;
                var userParent = um.GetUserParent(id.Value).ToList();
                if (userParent == null || userParent.Count == 0)
                {
                    id = LoginUserID;
                    data = data.Where(p => p.CommandID == id);
                    ViewData["msg"] = "您查看的用户不存在。".AlertOffPage();
                }
                else
                {
                    data = data.Where(p => p.Commands.EndsWith(LoginUserID.ToString()) || p.Commands.Contains(id.ToString()));
                }
                var userlist = data.ToArray().Select(p => new User_Comm { LoginName = p.LoginName, Uid = p.ID, CommandID = p.CommandID, Commmands = p.Commands, UserTye = p.UserType }).ToList();
                userlist.AddRange(userParent.Where(p => p.Commands.Contains(LoginUserID.ToString()) && p.CommandID != LoginUserID).Select(p => new User_Comm { LoginName = p.LoginName, Uid = p.Uid, CommandID = p.CommandID, Commmands = p.Commands, UserTye = p.UserType }));
                model = PassTreeView(user, userlist);
            }

            return View(model);
        }
        private Guid currentid;
        public TreeViewEntity PassTreeView(User_Comm user, IEnumerable<User_Comm> userList)
        {
            TreeViewEntity treeView = new TreeViewEntity();
            var list = userList.Where(p => p.CommandID == user.Uid);
            var isSurrogate = user.UserTye == (short)UserType.Surrogate;
            var nodeHtml = string.Format("{2}{0}&nbsp;&nbsp;<a href='{1}' title='转到会员管理'><font color='blue'>→</font></a>", currentid == user.Uid ? "<font color='red'>" + user.LoginName + "</font>" : user.LoginName, Url.Action("Childs", Url.Route(new { Where = new { ChildName = user.LoginName }, returnUrl = Url.Action("ChildView", new { id = user.Uid }) })), isSurrogate ? list.Count() == 0 ? "+" : "-" : "");
            treeView.NodeHtml = nodeHtml;
            treeView.NodeVlue = user.Uid.ToString();
            var classStr = "treeViewComm";
            if (isSurrogate)
            {
                classStr += "  SurrogateNode";
            }
            treeView.Attributes.Add("class", classStr);
            //var userMsg = string.Format("真实姓名:{0}\r\n当前余额:{1}\r\n注册时间:{2}",user.RName,user.Money,user.RegistTime);
            //treeView.Attributes.Add("title", userMsg);
            foreach (var item in list)
            {
                treeView.NodeList.Add(PassTreeView(item, userList));
            }
            return treeView;
        }

        public JsonResult LockUser(Guid uid)
        {
            var count = -1;
            var msg = "";
            var um = new UserManage();
            var user = um.Select(s => s.Where(p => p.ID == uid && p.CommandID == LoginUserID).Select(p => new { p.State }).FirstOrDefault());
            if (user != null)
            {
                if (user.State == (short)UserState.Normal || user.State == (short)UserState.Freez)
                {
                    count = um.Update(new NameValue<string, object> { { "State", UserState.Locked_Manage } }, new NameValue<string, object> { { "ID", uid } });
                    if (count > 0)
                        msg = "成功锁定";
                    else
                        msg = "操作失败！";
                }
                else
                    msg = "当前用户已被" + ((UserState)user.State).GetName();
            }
            else
                msg = "当前用户没找到。";
            return Json(new { msg, count }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult FreeUser(Guid uid)
        {
            var count = -1;
            var msg = "";
            var um = new UserManage();
            var user = um.Select(s => s.Where(p => p.ID == uid && p.CommandID == LoginUserID).Select(p => new { p.State }).FirstOrDefault());
            if (user != null)
            {
                if (user.State == (short)UserState.Locked_Manage)
                {
                    try
                    {
                        count = um.UserFreezeMoney(uid, UserState.Locked_Manage);
                        if (count > 0)
                            msg = "操作成功！";
                        else
                            msg = "操作失败！";
                    }
                    catch (AppException a)
                    {
                        msg = a.Message;
                    }
                    catch (Exception)
                    {
                        msg = "操作失败！";
                    }
                }
                else
                    msg = "当前用户没有被代理锁定";
            }
            else
                msg = "当前用户没找到";
            return Json(new { msg, count }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 会员管理

        public ActionResult Childs(ChildsModel model)
        {
            UserManage um = new UserManage();
            if (model == null)
                model = new ChildsModel();
            if (model.PageInfo == null)
                model.PageInfo = new PageInfo();

            if (model.Where == null || !string.IsNullOrEmpty(model.Where.ChildName))
            {
                if (model.Where != null)
                {
                    var user = um.Select(s => s.FirstOrDefault(p => p.LoginName == model.Where.ChildName && p.Commands.Contains(LoginUserID.ToString())));
                    if (user == null)
                    {
                        ViewData["msg"] = "您查找的下级不存在".AlertOffPage();
                        model.CurrentUid = LoginUserID;
                    }
                    else
                        model.CurrentUid = user.ID;
                }
                else if (model.CurrentUid.HasValue && model.CurrentUid != LoginUserID)
                {
                    var user = um.Select(s => s.FirstOrDefault(p => p.ID == model.CurrentUid.Value));
                    if (user != null)
                    {
                        var flag = user.Commands.Contains(LoginUserID.ToString());
                        if (!flag)
                        {
                            model.CurrentUid = LoginUserID;
                            ViewData["msg"] = "您要查看的用户不是您的下级".AlertOffPage();
                        }
                    }
                    else
                    {
                        ViewData["msg"] = "您要查找的下级不存在".AlertOffPage();
                        model.CurrentUid = LoginUserID;
                    }
                }
                else
                    model.CurrentUid = LoginUserID;
                model.MyChilds = um.GetUserParent(model.CurrentUid.Value).ToArray();
                model.ChildsCount = um.GetUserChilds(model.CurrentUid.Value).Count();
                var childs = um.GetUserChild(model.CurrentUid.Value, false, "");
                model.PageInfo.SunCount = childs.Count();
                childs = childs.OrderBy(p => p.RegistTime).Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount).ToList();
                model.Childs = childs.OrderBy(p => p.ChildName).ToArray();
            }
            else
            {
                model.CurrentUid = LoginUserID;
                string where = " 1==1 ";
                List<object> param = new List<object>();
                GetWhere(model.Where, out where, out param);
                var childs = um.GetUserChild(LoginUserID, false, where, param.ToArray());
                model.PageInfo.SunCount = childs.Count();
                childs = childs.OrderBy(p => p.RegistTime).Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount).ToList();
                model.Childs = childs.OrderBy(p => p.ChildName).ToArray();
            }
            model.LoginUserID = LoginUserID;
            return View(model);
        }
        [HttpPost]
        [ActionName("Childs")]
        public ActionResult Childs_Post([Bind(Exclude = "PageInfo,CurrentUid")]ChildsModel model)
        {
            if (ModelState.IsValid)
            {
                return Childs(model);
            }
            return Childs(null);
        }

        public ActionResult PlayTypeOption(LotteryTypeType? id, Guid? uid)
        {
            var model = new PlayTypeOptionModel();
            var LM = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort);
            model.Lotterys = new ModelNameValue<LotteryTypeType, string>(LM.Select(p => new NameValueItem<LotteryTypeType, string>(p.Key, p.Value.Name)));
            if (!uid.HasValue || LoginUserID == uid)
            {
                return RedirectToAction("Childs");
            }
            var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == uid.Value));
            if (user == null)
                return RedirectToAction("Childs");
            var flag = user.Commands.EndsWith(LoginUserID.ToString());
            if (!flag)
            {
                var msg = "您不能修改非直属下级的返奖信息";
                return RedirectToAction("Childs", new { Msg = msg });
            }
            if (id.HasValue)
                model.LotteryID = id;
            else if (!id.HasValue && model.Lotterys.Count > 0)
                model.LotteryID = model.Lotterys.First().Key;
            else
                model.LotteryID = (LotteryTypeType)(-1);

            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            var win = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
            if (model.UseSiteBackMoneyRatio && win==false)
            {
                ViewData["msg"] = "不能设置返点".AlertOffPage();
                ViewData["btnAddDisabled"] = true;
            }
            var MemberMaxSetRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            var PM = new PlayTypeOptionManage();
            model.Options = PM.GetOption_Set(user.ID, (int)model.LotteryID.Value.GetDefaultLottery(), null, true).ToArray();
            model.WinMoneyState = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
            model.Uid = user.ID;
            model.UserName = user.LoginName;

            return View(model);
        }

        [HttpPost]
        public ActionResult PlayTypeOption(PlayTypeOptionModel model)
        {
            if (model == null || model.Options == null)
                return RedirectToAction("PlayTypeOption");

            var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == model.Uid));
            if (user == null)
                return RedirectToAction("Childs");
            var flag = user.Commands.EndsWith(LoginUserID.ToString());
            if (!flag)
            {
                var msg = "您不能修改非直属下级的返奖信息";
                return RedirectToAction("Childs", new { Msg = msg });
            }
            model.UserName = user.LoginName;
            model.UseSiteWinMoney = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            var MemberMaxSetRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            PlayTypeOptionManage mana = new PlayTypeOptionManage();

            if (model.Options != null)
            {
                 if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true && CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false))
                {
                    int couts = 0;
                    foreach (var item in model.Options)
                    {
                        if (item.States == false)
                        {
                            couts++;
                        }
                    }

                    if (couts == model.Options.Count())
                    {
                        ViewData["msg"] = Url.Action("PlayTypeOption", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                        return View(model);
                    }
                    List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                    foreach (var item in model.Options)
                    {
                        int winId = item.Option.WinMoneyModelID;
                        int num = 0;
                        foreach (var MyWinId in model.Options)
                        {
                            if (winId == MyWinId.Option.WinMoneyModelID)
                            {
                                model.Options[num].States = item.States;
                            }
                            num++;
                        }

                    }
                    foreach (var item in model.Options)
                    {
                        Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                        back.BackMoneyRatio = item.Option.BackMoneyRatio;
                        back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                        back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                        var winId = item.Option.WinMoneyModelID;
                        back.States = item.States;
                        list.Add(back);
                    }
                    var number = mana.Updatewin(list, mana.Name(model.Uid).LoginName);
                    if (number>0)
                    {
                        ViewData["msg"] = Url.Action("PlayTypeOption", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");
                        return View(model);
                    }
                }
                 if (model.UseSiteBackMoneyRatio == false)
                 {
                     List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();

                     foreach (var item in model.Options)
                     {
                         int winId = item.Option.WinMoneyModelID;
                         int num = 0;
                         foreach (var MyWinId in model.Options)
                         {
                             if (winId == MyWinId.Option.WinMoneyModelID)
                             {
                                 model.Options[num].States = item.States;
                             }
                             num++;
                         }
                     }

                     if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true)
                     {
                         int i = 0;
                         foreach (var item in model.Options)
                         {
                             if (item.States == false)
                             {
                                 i++;
                             }
                         }

                         if (i == model.Options.Count())
                         {
                             ViewData["msg"] = Url.Action("PlayTypeOption", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                             return View(model);
                         }
                         else
                         {
                             foreach (var item in model.Options)
                             {
                                 Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                                 back.BackMoneyRatio = item.Option.BackMoneyRatio;
                                 back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                                 back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                                 var winId = item.Option.WinMoneyModelID;
                                 back.States = item.States;
                                 list.Add(back);
                             }



                             int result = mana.UpdateOption(list, model.Uid);
                             if (result < 0)
                                 ViewData["msg"] = "操作失败！请稍后重试。".AlertOffPage("msg.value = '';", false);
                             else
                                 ViewData["msg"] = Url.Action("PlayTypeOption", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");
                         }
                     }
                     else
                     {
                         foreach (var item in model.Options)
                         {
                             Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                             back.BackMoneyRatio = item.Option.BackMoneyRatio;
                             back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                             back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                             var winId = item.Option.WinMoneyModelID;
                             back.States = true;
                             list.Add(back);
                         }
                         int result = mana.UpdateOptionUser(list, model.Uid);
                         if (result < 0)
                             ViewData["msg"] = "操作失败！请稍后重试。".AlertOffPage("msg.value = '';", false);
                         else
                             ViewData["msg"] = Url.Action("PlayTypeOption", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");

                     }
                 }
            }
            else
            {
                return Redirect(Url.Action("PlayTypeOption", new { model.Uid, id = model.LotteryID }).Redirect("参数不正确！"));
            }


            model.Options = mana.GetOption_Set(user.ID, 1, null, true).ToArray();

            model.Options.Each(p => p.MaxBackMoneyRatio = Math.Min(MemberMaxSetRatio, p.MaxBackMoneyRatio));
            model.Uid = user.ID;
            model.UserName = user.LoginName;
            return View(model);
        }

        public JsonResult UpUser(Guid id)
        {
            string msg;
            var count = -1;
            var um = new UserManage();
            var flag = um.Select(s => s.Select(p => p.ID == id && p.Commands.EndsWith(LoginUserID.ToString()) && p.UserType == (short)UserType.Member).Contains(true));
            if (flag)
            {
                count = um.UpdateUserType(id, out msg, true);
            }
            else
                msg = "操作失败!请确定当前用户是否为您的直属下级或已为代理。";
            return Json(new { msg, count }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult SubWinMoneyMargin(Guid id)
        {
            var UM = new UserManage();
            var user = UM.Select(s => s.Where(p => p.CommandID == LoginUserID).Select(p => new { p.ID, p.LoginName }).FirstOrDefault(p => p.ID == id));
            if (user == null)
                return Content(Url.Action("AllUser").Redirect("不存在该用户！"));

            var model = new SubWinMoneyMarginModel() { ID = id, UserName = user.LoginName };
            model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Value.ID }).ToList();
            model.WinModels.Insert(0, new SelectListItem { Text = "选择模式", Value = "" });
            model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.Lottery == p.Key }).ToList();
            model.Lotters.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            return View(model);
        }

        [HttpPost]
        public ActionResult SubWinMoneyMargin(SubWinMoneyMarginModel model)
        {
            if (model != null)
            {
                model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Value.ID }).ToList();
                model.WinModels.Insert(0, new SelectListItem { Text = "选择模式", Value = "" });
                model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.Lottery == p.Key }).ToList();
                model.Lotters.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            }
            if (ModelState.IsValid)
            {
                LotteryType? lottery = model.Lottery.HasValue ? (model.Lottery.Value.GetDefaultLottery()) as LotteryType? : null;
                var PM = new PlayTypeOptionManage();
                int rs = PM.SetUserOptionByMargin(LoginUserID, model.ID, model.WinModelID, lottery, model.WinMoneyRatio, model.BackMoneyRatioMargin, false, false);
                if (rs > 0)
                    return Content("".Redirect("调整完成！"));
                else if (rs == 0)
                    return Content("".Redirect("无操作！"));
                else
                    ViewData["msg"] = "操作失败，请稍后再试！".AlertOffPage();

            }
            return View(model);
        }

        public ActionResult SetWinMoneyMargin()
        {
            if (Code.BLL.CacheManage.OptionSite[Code.Models.Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false) || Code.BLL.CacheManage.OptionSite[Code.Models.Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false)) 
            {
                ViewData["msg"] = "您不能设置奖金和返点，请和上级或管理员联系!".AlertOffPage();
                ViewData["btnAddDisabled"] = true;
            
            }

            var model = new SubWinMoneyMarginModel() { ID = LoginUserID, UserName = LoginUser.LoginName };
            model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Value.ID }).ToList();
            model.WinModels.Insert(0, new SelectListItem { Text = "选择模式", Value = "" });
            model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.Lottery == p.Key }).ToList();
            model.Lotters.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            return View(model);
        }

        [HttpPost]
        public ActionResult SetWinMoneyMargin(SubWinMoneyMarginModel model)
        {

            if (model != null)
            {
                model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Value.ID }).ToList();
                model.WinModels.Insert(0, new SelectListItem { Text = "选择模式", Value = "" });
                model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.Lottery == p.Key }).ToList();
                model.Lotters.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            }
            if (ModelState.IsValid)
            {
                LotteryType? lottery = model.Lottery.HasValue ? (model.Lottery.Value.GetDefaultLottery()) as LotteryType? : null;
                var PM = new PlayTypeOptionManage();
                int rs = PM.SetUserSubWinMoneyMargin(LoginUserID, model.WinModelID, lottery, model.WinMoneyRatio, model.BackMoneyRatioMargin, false);
                if (rs > 0)
                    return Content("".Redirect("调整完成！"));
                else if (rs == 0)
                    return Content("".Redirect("无操作！"));
                else
                    ViewData["msg"] = "操作失败，请稍后再试！".AlertOffPage();
            }
            return View(model);
        }

        public ActionResult SetAddChildConfig(PageInfo pageInfo, SetAddChildConfigModel.SerchUser serch)
        {
            var enableAddChildConfig = CacheManage.OptionSite[Option_Site_Key.Site_AddChildConfig_Enable].ToBool(false);
            if (!enableAddChildConfig)
            ViewData["msg"] = Url.Action("Index","Home").Redirect("系统已关闭配额设置，您不能进行此操作！");
            var acc = new AddChildConfigManage();
            var temp = acc.Select(s => s.Where(p => p.UserID == LoginUserID || p.Users.CommandID == LoginUserID));
            if (serch != null)
            {
                if (!string.IsNullOrEmpty(serch.Name))
                    temp = temp.Where(p => p.UserID == LoginUserID || p.Users.LoginName == serch.Name);
                if (serch.MaxCount_AllChild.HasValue)
                    temp = temp.Where(p => p.UserID == LoginUserID || p.AllChildCount <= serch.MaxCount_AllChild.Value);
                if (serch.MinCount_AllChild.HasValue)
                    temp = temp.Where(p => p.UserID == LoginUserID || p.AllChildCount >= serch.MinCount_AllChild.Value);
            }
            var data = temp.Select(p => new AddChildConfigModel
            {
                AllChildCount = p.AllChildCount,
                uid = p.Users.ID,
                UserType = p.Users.UserType,
                UserName = p.Users.LoginName
            }).ToList();
            var list = acc.Select(s => s.Where(p => s.Where(pp => pp.Users.CommandID == LoginUserID).Select(pp => pp.UserID).Contains(p.Users.CommandID.Value)).Select(p => new { acc = p, p.Users.CommandID, p.Users.UserType })).ToArray();
            data.Each(p =>
            {
                if (p.uid == LoginUserID)
                {
                    var tempList = data.Where(pp => pp.uid != p.uid);
                    p.NowChildCount = p.AllChildCount - tempList.Sum(pp => pp.AllChildCount) - tempList.Count();
                }
                else
                {
                    var tempList = list.Where(pp => pp.CommandID == p.uid);
                    p.NowChildCount = p.AllChildCount - tempList.Sum(pp => pp.acc.AllChildCount) - tempList.Count();
                }
            });
            if (serch != null)
            {
                if (serch.MaxCount.HasValue)
                    data = data.Where(p => p.uid == LoginUserID || p.NowChildCount <= serch.MaxCount).ToList();
                if (serch.MinCount.HasValue)
                    data = data.Where(p => p.uid == LoginUserID || p.NowChildCount >= serch.MinCount).ToList();
            }
            //data = data.Where(p => p.UserType == (short)UserType.Surrogate).ToList();
            var model = new SetAddChildConfigModel();
            if (pageInfo != null)
                model.PageInfo = pageInfo;
            if (model.PageInfo == null)
                model.PageInfo = new PageInfo();
            model.PageInfo.SunCount = data.Count - 1;
            var me = data.FirstOrDefault(p => p.uid == LoginUserID);
            model.UsersConfig = data.Where(p => p.uid != LoginUserID).Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount).OrderByDescending(p => p.AllChildCount).ToList();
            model.UsersConfig.Insert(0, me);
            model.LoginUid = LoginUserID;
            if (serch != null)
                model.Serch = serch;
            return View(model);
        }

        [HttpPost]
        public ActionResult SetAddChildConfig(SetAddChildConfigModel.SerchUser serch)
        {
            return SetAddChildConfig(null, serch);
        }

        public JsonResult UpdateAddChildConfig(SetAddChildConfigModel model)
        {
            if (!ModelState.IsValid)
                return Json(new { msg = "数据有误!", count = -1 }, JsonRequestBehavior.AllowGet);
            var acc = new AddChildConfigManage();
            var tempOldValue = acc.Select(s => s.FirstOrDefault(p => p.UserID == model.Uid && p.Users.UserType == (short)UserType.Surrogate));
            if (tempOldValue == null)
                return Json(new { msg = "当前用户未找到", count = -1 }, JsonRequestBehavior.AllowGet);
            model.OldACCValue = tempOldValue.AllChildCount;
            var tempme = acc.GetNowAddChildConfig(LoginUserID);
            var tempu = acc.GetNowAddChildConfig(model.Uid);
            var accN = model.ACCValue - model.OldACCValue;
            if (accN > 0 && tempme.AllChildCount < accN)
                return Json(new { msg = "您的可用配额不足", count = -1 }, JsonRequestBehavior.AllowGet);
            else if (accN < 0 && tempu.AllChildCount < -accN)
                return Json(new { msg = "当前用户的可用配额不足", count = -1 }, JsonRequestBehavior.AllowGet);

            var update = new NameValue<string, object>
            {
                {"AllChildCount",model.ACCValue},
                {"AllSurrogateCount",0}
            };
            var where = new NameValue<string, object>
            {
                {"UserID",model.Uid}
            };
            int count = acc.Update(update, where);
            return Json(new { msg = count > 0 ? "操作成功！" : "操作失败，请稍后再试！", count }, JsonRequestBehavior.AllowGet);
        }


        #endregion

        #region 团队账变
        public ActionResult AccountDetail(DetailModel model)
        {
            if (model == null)
                model = new DetailModel();
            if (model.Serch == null)
                model.Serch = new UserManage.UserAccountDetailSerch();

            model.Types = (Enum.GetValues(typeof(UserAccountDetailType)) as UserAccountDetailType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.Types.Insert(0, new SelectListItem { Text = "所有明细", Value = string.Empty });
            model.UserTypes = (Enum.GetValues(typeof(UserType)) as UserType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.UserTypes.Insert(0, new SelectListItem { Text = "所有组", Value = string.Empty });

            if (ModelState.IsValid)
            {
                if (model.PageSize <= 0)
                    model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15);
                if (!model.Page.HasValue)
                    model.Page = 1;

                UserManage UM = new UserManage();
                if (model.uid.HasValue)
                {
                    var user = UM.Select(s => s.FirstOrDefault(p => p.ID == model.uid));
                    if (user == null)
                        ViewData["msg"] = "用户不存在".AlertOffPage();
                    else if (user.UserType != (short)UserType.Surrogate)
                        ViewData["msg"] = "用户不是代理".AlertOffPage();
                }

                var report = UM.GetUserAccountDetail(model.Serch, base.LoginUserID, model.uid).Where(p => p.UserID != LoginUserID);
                if (model.uid.HasValue)
                    report = report.Where(p => p.UserID != model.uid.Value);

                model.SumCount = report.Count();
                if (model.SumCount > 0)
                {
                    var reg = new Regex(@"^\w{1,}:[-0-9]{1,}期", RegexOptions.Compiled);
                    model.SumDetail = report.GroupBy(p => 1).Select(p => new QianBuo.Lottery.Web.Models.Account.AccountDetail { InMoney = p.Sum(pp => pp.InMoney), OutMoney = p.Sum(pp => pp.OutMoney) }).FirstOrDefault() ?? new QianBuo.Lottery.Web.Models.Account.AccountDetail();
                    model.Details = report.OrderBy("AddTime DESC,Type").Skip(model.PageSize * (model.Page.Value - 1)).Take(model.PageSize)
                        .Select(p => new QianBuo.Lottery.Web.Models.Account.AccountDetail { LoginName = p.LoginName, UserType = p.UserType, ID = p.ID, AddTime = p.AddTime, Memo = p.Memo, State = p.State, InMoney = p.InMoney, OutMoney = p.OutMoney, Type = (UserAccountDetailType)p.Type }).ToList();
                    model.Details.Each(p =>
                    {
                        int? state; int tp;
                        state = int.TryParse(p.State, out tp) ? tp as int? : null;
                        if ((p.Type == UserAccountDetailType.QuashScheme || p.Type == UserAccountDetailType.Other) && p.ID != null && (p.Info = p.ID.Split('&').Select(pp => { var nv = pp.Split(':'); return new { N = nv[0], V = nv[1] }; }).ToDictionary(pp => pp.N, pp => pp.V)).Count > 0)
                            p.ID = p.Info.ContainsKey("RefID") ? p.Info["RefID"] : null;
                        if (p.Type == UserAccountDetailType.AddMoney) p.StateText = ((AddMoneyType)state).GetName();
                        if (p.Type == UserAccountDetailType.BackMoney_Child || p.Type == UserAccountDetailType.WinMoney_Child || p.Type == UserAccountDetailType.Play ||
                            p.Type == UserAccountDetailType.WinMoney || p.Type == UserAccountDetailType.QuashScheme || p.Type == UserAccountDetailType.BackMoney ||
                            (p.Type == UserAccountDetailType.Other && state == (short)OtherMoneyDetailType.BackTimeOutScheme))
                        {
                            if (reg.IsMatch(p.Memo ?? string.Empty))
                            {
                                int i1 = p.Memo.IndexOf(":");
                                int i2 = p.Memo.IndexOf("期");
                                var str = p.Memo.Substring(0, i1);
                                LotteryType l = (LotteryType)int.Parse(str);
                                str = p.Memo.Substring(i1 + 1, i2 - i1 - 1);
                                var str1 = Issue.PastIssueName(l, str);
                                p.Memo = string.Format("{0}:{1}{2}", l.GetName(), str1, p.Memo.Substring(i2));
                            }
                        }
                        if (p.Type == UserAccountDetailType.Other && state.HasValue) { p.StateText = ((OtherMoneyDetailType)state).GetName(); }
                        //if (p.Type == UserAccountDetailType.Play && state.HasValue) p.StateText = ((SchemeState)state).GetName();
                        if (p.Type == UserAccountDetailType.ChaseTask && state.HasValue) { p.StateText = ((ChaseTaskState)state).GetName(); p.Memo = ((LotteryType)int.Parse(p.Memo)).GetName() + "追号任务"; }
                        if (p.Type == UserAccountDetailType.Freez && state.HasValue) { p.StateText = ((FreezeMoneyDetailState)state).GetName(); p.Memo = ((FreezeCause)int.Parse(p.Memo)).GetName(); }

                    });
                }
            }

            return View(model);
        }
        #endregion

        #region 团队报表
        public ActionResult AccountReport(Models.Surrogate.AccountReportModel model)
        {
            if (model.PageSize <= 0)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(20);
            if (model.Page <= 0)
                model.Page = 1;
            model.UserTypes = (Enum.GetValues(typeof(UserType)) as UserType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.UserTypes.Insert(0, new SelectListItem { Text = "所有组", Value = string.Empty });

            var UM = new UserManage();
            if (model.uid.HasValue)
            {
                var user = UM.Select(s => s.FirstOrDefault(p => p.ID == model.uid));
                if (user == null)
                    ViewData["msg"] = "用户不存在".AlertOffPage();
                else if (user.UserType != (short)UserType.Surrogate)
                    ViewData["msg"] = "用户不是代理".AlertOffPage();
            }
            model.MinSerchTime = (UM.Select<UserAccountDetail, UserAccountDetail>(s => s.OrderBy(p => p.AddTime).FirstOrDefault()) ?? new UserAccountDetail { AddTime = DateTime.Now }).AddTime;
            model.MaxSerchTime = DateTime.Now;

            var report = UM.GetUserAccountReport(model.Serch, LoginUserID, model.uid).Where(p => p.UserID != LoginUserID);
            if (model.uid.HasValue)
                report = report.Where(p => p.UserID != model.uid.Value);
            var rs = report.GroupBy(p => new { p.UserID, p.LoginName, p.UserType })
                .Select(p => new Models.Surrogate.AccountReport
                {
                    LoginName = p.Key.LoginName,
                    UserID = p.Key.UserID,
                    UserType = p.Key.UserType,
                    AddMoney = p.Sum(pp => pp.SumAddMoney),
                    TackMoney = p.Sum(pp => pp.SumTackMoney),
                    PlayMoney = p.Sum(pp => pp.SumPlayMoney),
                    BackMoney = p.Sum(pp => pp.SumBackMoney),
                    BackMoney_Child = p.Sum(pp => pp.SumBackMoney_Child),
                    WinMoney = p.Sum(pp => pp.SumWinMoney),
                    WinMoney_Child = p.Sum(pp => pp.SumWinMoney_Child)
                });

            model.SumCount = rs.Count();

            if (model.SumCount > 0)
            {
                model.SumReport = report.GroupBy(p => 1).Select(p => new Models.Surrogate.AccountReport
                {
                    AddMoney = p.Sum(pp => pp.SumAddMoney),
                    TackMoney = p.Sum(pp => pp.SumTackMoney),
                    PlayMoney = p.Sum(pp => pp.SumPlayMoney),
                    BackMoney = p.Sum(pp => pp.SumBackMoney),
                    BackMoney_Child = p.Sum(pp => pp.SumBackMoney_Child),
                    WinMoney = p.Sum(pp => pp.SumWinMoney),
                    WinMoney_Child = p.Sum(pp => pp.SumWinMoney_Child)
                }).First();
                model.Reports = rs.OrderByDescending(p => p.LoginName).Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize);
            }

            return View(model);
        }

        public ActionResult TeamReport(TeamReportModel model)
        {
            if (model == null)
                model = new TeamReportModel();
            if (model.Search == null)
                model.Search = new UserManage.UserAccountDetailSerch();
            if (!model.Search.StartTime.HasValue)
            {
                var span = DateTime.Now.Hour >= 6 ? 0 : -1;
                model.Search.StartTime = DateTime.Now.Date.AddDays(span).AddHours(6);
            }
            var page = model.Page ?? 1;
            var size = model.PageSize ?? 10;
            if (page < 1)
                page = 1;
            if (size < 1)
                size = 10;
            model.Lotterys = CacheManage.Lottery.Values.OrderBy(p => p.Sort).Select(p => new SelectListItem { Text = p.Name, Value = p.Alias, Selected = model.Lottery == (LotteryType)p.ID }).ToList();
            model.Lotterys.Insert(0, new SelectListItem { Text = "所有彩种", Value = "" });

            if (!string.IsNullOrEmpty(model.Search.LoginName))
                model.Uid = null;

            var uid = model.Uid;
            var UM = new UserManage();

            Code.Models.Users user = null;
            if (!string.IsNullOrEmpty(model.Search.LoginName))
            {
                user = UM.Select(s => s.FirstOrDefault(p => p.LoginName == model.Search.LoginName));
                if (user != null && (LoginUserID == user.ID || user.Commands.Contains(LoginUserID.ToString().ToLower())))
                    uid = user.CommandID;
            }
            uid = uid ?? LoginUserID;
            if (user == null)
                user = UM.Select(s => s.First(p => p.ID == uid && (LoginUserID == p.ID || p.Commands.Contains(LoginUserID.ToString().ToLower()))));
            if (user == null)
            {
                ViewData["msg"] = "不存在该用户".AlertOffPage();
                return View(model);
            }
            if (uid != LoginUserID)
            {
                var cmd = user.Commands.Substring(LoginUser.Commands.Length).Split("&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => new Guid(p)).ToArray();
                model.Path = UM.Select(s => s.Where(p => cmd.Contains(p.ID) || p.ID == uid).OrderBy(p => p.Commands.Length).Select(p => new Key<string, Guid>(p.LoginName, p.ID))).ToArray();
            }
            ViewData["CurrentCmd"] = uid;
            var data = UM.GetUserAccountDetail(model.Search, model.Uid, LoginUserID);

            var types = new int[] { (int)UserAccountDetailType.BackMoney_Child, (int)UserAccountDetailType.WinMoney_Child, (int)UserAccountDetailType.Play, (int)UserAccountDetailType.WinMoney, (int)UserAccountDetailType.BackMoney };
            if (model.Lottery.HasValue)
                data = data.Where(p => !types.Contains(p.Type) || p.Memo.StartsWith(((int)model.Lottery) + ":"));
            var ds = data.ToArray();
            var users = UM.Select(s => s.Where(p => p.ID == uid || p.CommandID == uid).Select(p => new { UserID = p.ID, p.LoginName, p.UserType })).ToArray();
            var self = users.FirstOrDefault(p => p.UserID == uid);
            var childs = users.Where(p => p.UserID != uid).Select(p => p).ToArray();
            var states = new string[] { ((int)SchemeState.Opened).ToString(), ((int)SchemeState.Normal).ToString(), ((int)SchemeState.OutBill).ToString() };
            var datas = ds.GroupBy(p => new { p.UserID, p.LoginName, p.UserType, p.Commands })
                .Select(p =>
                {
                    var u = childs.FirstOrDefault(pp => p.Key.UserID == pp.UserID || p.Key.Commands.Contains(pp.UserID.ToString().ToLower())) ?? self;
                    return new
                    {
                        u.UserID,
                        u.UserType,
                        u.LoginName,
                        AddMoney = p.Sum(pp => pp.Type == (int)UserAccountDetailType.AddMoney ? pp.Money : 0),
                        TackMoney = p.Sum(pp => pp.Type == (int)UserAccountDetailType.TackMoney ? pp.Money : 0),
                        BackMoney = p.Sum(pp => pp.Type == (int)UserAccountDetailType.BackMoney ? pp.Money : 0),
                        BackMoney_Child = p.Sum(pp => pp.Type == (int)UserAccountDetailType.BackMoney_Child ? pp.Money : 0),
                        PlayMoney = p.Sum(pp => pp.Type == (int)UserAccountDetailType.Play && states.Contains(pp.State) ? pp.Money : 0),
                        WinMoney = p.Sum(pp => pp.Type == (int)UserAccountDetailType.WinMoney ? pp.Money : 0),
                        WinMoney_Child = p.Sum(pp => pp.Type == (int)UserAccountDetailType.WinMoney_Child ? pp.Money : 0)
                    };
                }).GroupBy(p => new { p.UserID, p.LoginName, p.UserType }, (p, s) => new AccountReport
                {
                    UserID = p.UserID,
                    UserType = p.UserType,
                    LoginName = p.LoginName,
                    AddMoney = s.Sum(t => t.AddMoney),
                    TackMoney = s.Sum(t => t.TackMoney),
                    BackMoney = s.Sum(t => t.BackMoney),
                    BackMoney_Child = s.Sum(t => t.BackMoney_Child),
                    PlayMoney = s.Sum(t => t.PlayMoney),
                    WinMoney = s.Sum(t => t.WinMoney),
                    WinMoney_Child = s.Sum(t => t.WinMoney_Child)
                }).ToList();
            model.SumCount = datas.Count;
            model.SelfReport = datas.FirstOrDefault(p => p.UserID == uid);
            model.Report = datas.Where(p => p.UserID != uid).OrderBy(p => p.LoginName).Skip(size * (page - 1)).Take(size);
            model.SumReport = datas.GroupBy(p => 1, (p, s) => new AccountReport
            {
                AddMoney = s.Sum(t => t.AddMoney),
                TackMoney = s.Sum(t => t.TackMoney),
                BackMoney = s.Sum(t => t.BackMoney),
                BackMoney_Child = s.Sum(t => t.BackMoney_Child),
                PlayMoney = s.Sum(t => t.PlayMoney),
                WinMoney = s.Sum(t => t.WinMoney),
                WinMoney_Child = s.Sum(t => t.WinMoney_Child)
            }).FirstOrDefault();

            return View(model);
        }
        #endregion

        #region 团队余额
        public ActionResult GroupMoney(GroupMoneyModel model)
        {
            var um = new UserManage();
            var IsSurrogate = true;
            if (model == null)
            {
                model = new GroupMoneyModel();
                model.LoginUid = LoginUserID;
                model.CurrenUid = LoginUserID;
            }
            else
            {
                if (model.LoginUid == null)
                    model.LoginUid = LoginUserID;
                if (model.CurrenUid == null && string.IsNullOrEmpty(model.UserName))
                    model.CurrenUid = LoginUserID;
                else if (model.CurrenUid == null)
                {
                    var user = um.Select(s => s.FirstOrDefault(p => p.LoginName == model.UserName.Trim()));
                    if (user == null)
                    {
                        ViewData["msg"] = "没有您要查找的用户".AlertOffPage();
                        model.CurrenUid = LoginUserID;
                    }
                    else
                    {
                        var flag = user.Commands.Contains(LoginUserID.ToString());
                        if (!flag)
                        {
                            ViewData["msg"] = "您要查看的用户不是您的下级".AlertOffPage();
                            model.CurrenUid = LoginUserID;
                        }
                        else
                        {
                            model.CurrenUid = user.ID;
                            IsSurrogate = user.UserType == (short)UserType.Surrogate;
                        }
                    }
                }
                else if (model.CurrenUid != LoginUserID)
                {
                    var user = um.Select(s => s.FirstOrDefault(p => p.ID == model.CurrenUid));
                    if (user == null)
                    {
                        ViewData["msg"] = "没有您要查找的用户".AlertOffPage();
                        model.CurrenUid = LoginUserID;
                    }
                    else
                    {
                        var flag = user.Commands.Contains(LoginUserID.ToString());
                        if (!flag)
                        {
                            ViewData["msg"] = "您要查看的用户不是您的下级".AlertOffPage();
                            model.CurrenUid = LoginUserID;
                        }
                        else
                            IsSurrogate = user.UserType == (short)UserType.Surrogate;
                    }
                }
            }
            model.CurrentUserCommands = um.GetUserParent(model.CurrenUid.Value).ToDictionary(p => new Key<Guid, Guid?>(p.Uid, p.CommandID), p => p.LoginName);
            if (model.PageInfo == null)
                model.PageInfo = new PageInfo();
            if (IsSurrogate)
            {
                //整个团队账户统计
                var allSumData = um.Select(s => s.Where(p => p.Commands.Contains(model.CurrenUid.ToString())).GroupBy(p => 1).Select(p => new GroupMoneyModel.AccountDetail
                {
                    Balance = (double)p.Sum(p1 => p1.Account.Balance),
                    Freez = (double)p.Sum(p1 => p1.Account.FreezeMoney),
                    AddMoney = (double)p.Sum(p1 => p1.Account.AddMoney),
                    BackMoney = (double)p.Sum(p1 => p1.Account.BackMoney),
                    BackMoney_Child = (double)p.Sum(p1 => p1.Account.BackMoney_Child),
                    Buy = (double)p.Sum(p1 => p1.Account.BuyLottery),
                    TackMoney = (double)p.Sum(p1 => p1.Account.TackMoney),
                    WinMoney = (double)p.Sum(p1 => p1.Account.WinMoney),
                    WinMoney_Child = (double)p.Sum(p1 => p1.Account.WinMoney_Child)
                }).FirstOrDefault());
                if (allSumData == null)
                    allSumData = new GroupMoneyModel.AccountDetail();
                else if (model.StartTime.HasValue || model.EndTime.HasValue)
                {
                    var temp = um.Select<UserAccountReport, IEnumerable<UserAccountReport>>(s => s.Where(p => p.Commands.Contains(model.CurrenUid.ToString())));
                    if (model.StartTime.HasValue)
                        temp = temp.Where(p => p.Date >= model.StartTime.Value.Date);
                    if (model.EndTime.HasValue)
                        temp = temp.Where(p => p.Date <= model.EndTime.Value.Date);
                    temp = temp.GroupBy(p => 1).FirstOrDefault();
                    allSumData = new GroupMoneyModel.AccountDetail
                    {
                        Balance = allSumData.Balance,
                        Freez = allSumData.Freez,
                        AddMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumAddMoney),
                        BackMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumBackMoney),
                        BackMoney_Child = temp == null ? 0d : (double)temp.Sum(p => p.SumBackMoney_Child),
                        Buy = temp == null ? 0d : (double)temp.Sum(p => p.SumPlayMoney),
                        TackMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumTackMoney),
                        WinMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumWinMoney),
                        WinMoney_Child = temp == null ? 0d : (double)temp.Sum(p => p.SumWinMoney_Child)
                    };
                }
                model.AllChildsAccountSum = allSumData;
            }
            var data = um.Select(s => s.Where(p => p.Commands.EndsWith(model.CurrenUid.ToString())));
            if (!string.IsNullOrEmpty(model.UserName))
                data = um.Select(s => s.Where(p => p.ID == model.CurrenUid));
            model.PageInfo.SunCount = data.Count();
            if (model.StartTime.HasValue || model.EndTime.HasValue)
            {
                var str = "";
                var ps = new List<object>();
                if (model.StartTime.HasValue)
                {
                    str = " Date>=@" + ps.Count;
                    ps.Add(model.StartTime.Value.Date);
                }
                if (model.EndTime.HasValue)
                {
                    str += (ps.Count == 1 ? " And " : "") + " Date<=@" + ps.Count;
                    ps.Add(model.EndTime.Value.Date);
                }
                var temp = um.Select<UserAccountReport, IEnumerable<UserAccountReport>>(s => s.Where(str, ps.ToArray()));
                model.ChildAccountDetail = data.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount)
                   .GroupJoin(temp, p => p.ID, p => p.UserID, (p1, p2) => new { user = p1, uar = p2 })
                    .ToDictionary(p => p.user.ID, p => new GroupMoneyModel.AccountDetail
                    {
                        LoginName = p.user.LoginName,
                        UserType = p.user.UserType,
                        Balance = (double)p.user.Account.Balance,
                        Freez = (double)p.user.Account.FreezeMoney,
                        AddMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumAddMoney),
                        BackMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumBackMoney),
                        BackMoney_Child = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumBackMoney_Child),
                        Buy = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumPlayMoney),
                        TackMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumTackMoney),
                        WinMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumWinMoney),
                        WinMoney_Child = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumWinMoney_Child)
                    });
            }
            else
            {
                model.ChildAccountDetail = data.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount)
                    .ToDictionary(p => p.ID, p => new GroupMoneyModel.AccountDetail
                    {
                        LoginName = p.LoginName,
                        UserType = p.UserType,
                        Balance = (double)p.Account.Balance,
                        Freez = (double)p.Account.FreezeMoney,
                        AddMoney = (double)p.Account.AddMoney,
                        BackMoney = (double)p.Account.BackMoney,
                        BackMoney_Child = (double)p.Account.BackMoney_Child,
                        Buy = (double)p.Account.BuyLottery,
                        TackMoney = (double)p.Account.TackMoney,
                        WinMoney = (double)p.Account.WinMoney,
                        WinMoney_Child = (double)p.Account.WinMoney_Child
                    });
            }
            return View(model);
        }
        #endregion

        #region 给下级充值
        public ActionResult MoveMoney(MoveMoneyModel model)
        {
            var canAddMoney = CacheManage.OptionSite[Option_Site_Key.User_CanAddSubMoney].ToBool(false);
            if (!canAddMoney)
                return Content("<script>alert('当前功能已关闭');window.history.go(-1);</script>");
            if (ModelState.IsValid)
            {
                var um = new UserManage();
                var flag = um.BoolTakePwd(LoginUserID, model.PassWord);
                if (!flag)
                    ModelState.AddModelError("PassWord", "密码错误");
                else
                {
                    var user = um.Select(s => s.Where(p => p.LoginName == model.ChildName && p.CommandID == LoginUserID).FirstOrDefault());
                    flag = user == null;
                    if (flag)
                        ModelState.AddModelError("ChildName", "未找到您指定的用户");
                    else
                    {
                        var result = um.MoveMoney(LoginUserID, LoginUser.LoginName, user.ID, model.ChildName, model.Money.Value);
                        if (result == -2)
                            ModelState.AddModelError("Money", "您当前可用余额不足");
                        else if (result > 0)
                            ViewData["msg"] = "".Redirect("已成功从您账户转出指定金额到指定用户账下。");
                        else
                            ViewData["msg"] = "操作失败！请稍后再试!".AlertOffPage();
                    }
                }
                if (ModelState.IsValid)
                    model = new MoveMoneyModel();
            }
            return View(model);
        }
        #endregion
    }
}
